package cn.xutongxue.gtms.utils.excel;

import cn.xutongxue.gtms.exception.BusinessException;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

import static cn.xutongxue.gtms.utils.excel.ExportListener.getServletOutputStream;

@Slf4j
@SuppressWarnings("unchecked")
public class ExcelUtil<T, E> {

    private final IService<T> baseService;

    private Class<E> source = null;


    public ExcelUtil(IService<T> baseService) {
        this.baseService = baseService;
    }


    public ExcelUtil(IService<T> baseService, Class<E> source) {
        this.baseService = baseService;
        this.source = source;
    }


    /**
     * 导出Excel字节流
     *
     * @param response
     * @param sheetName    Excel文件名称和sheet名称
     * @param pojoClass    导出Excel实体类
     * @param queryWrapper 查询条件
     */
    public void exportToDownload(HttpServletResponse response, String sheetName, Class<T> pojoClass, LambdaQueryWrapper<T> queryWrapper) {
        try {
            long beforeTime = System.currentTimeMillis();
            new ExportListener<>(baseService).exportExcel(response, sheetName, pojoClass, queryWrapper);
            long afterTime = System.currentTimeMillis();
            log.info("导出登录日志excel耗时:{}", afterTime - beforeTime);
        } catch (Exception e) {
            throw new BusinessException("未知错误：" + e.getMessage());
        }
    }

    /**
     * 导入Excel表格
     *
     * @param file      文件流
     * @param pojoClass 导入Excel实体类
     */
    public void importToDatabase(MultipartFile file, Class<E> pojoClass) {
        try {
            long beforeTime = System.currentTimeMillis();
            EasyExcel.read(file.getInputStream(), pojoClass, new ImportListener(baseService)).sheet().headRowNumber(1).doRead();
            long afterTime = System.currentTimeMillis();
            log.info("导入操作日志耗时:{}", afterTime - beforeTime);
        } catch (Exception e) {
            throw new BusinessException("未知错误：" + e.getMessage());
        }
    }

    /**
     * 导入Excel表格
     *
     * @param file      文件流
     * @param pojoClass 导入Excel实体类
     */
    public void importToDatabaseStudent(MultipartFile file, Class<E> pojoClass) {
        try {
            long beforeTime = System.currentTimeMillis();
            EasyExcel.read(file.getInputStream(), pojoClass, new StudentImportListener<>(baseService)).sheet().headRowNumber(1).doRead();
            long afterTime = System.currentTimeMillis();
            log.info("导入操作日志耗时:{}", afterTime - beforeTime);
        } catch (Exception e) {
            throw new BusinessException("未知错误：" + e.getMessage());
        }
    }

    /**
     * 下载导入模板
     *
     * @param response
     * @param sheetName Excel文件名和sheet名称
     * @param pojoClass 导入Excel实体类
     * @throws IOException
     */
    public void downloadModel(HttpServletResponse response, String sheetName, Class<T> pojoClass) {
        try {
            ServletOutputStream out = getServletOutputStream(response, sheetName);
            // 这里 需要指定写用哪个class去写
            ExcelWriter excelWriter = EasyExcel.write(out, pojoClass).build();
            // 这里注意 如果同一个sheet只要创建一次
            WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
            // 千万别忘记finish 会帮忙关闭流
            excelWriter.write(new ArrayList<>(), writeSheet);
            excelWriter.finish();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
